//
//  KYHomeTableViewController.swift
//  01-我的微博
//
//  Created by apple on 15/7/28.
//  Copyright © 2015年 KY. All rights reserved.
//

import UIKit

class KYHomeTableViewController: KYBasicTableViewController {
    
    var statuses: [KYStatus]? {
        didSet{
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !KYUserAccountModel.userLogon {
            visitorView?.setupInfo(isHome: true, imageName: "visitordiscover_feed_image_smallicon", message: "关注一些人，回这里看看有什么惊喜")
            return
        }
        prepareTableView()
        loadData()
        
        // 下拉刷新
        refreshControl = KYRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)

        
        
        //行高预估是 300
        tableView.estimatedRowHeight = 300
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    
    private func prepareTableView() {
        
        
        tableView.registerClass(KYStatusNomalCell.self, forCellReuseIdentifier: KYStatusCellIdentifier.NormalCell.rawValue)
        tableView.registerClass(KYStatusForwardCell.self, forCellReuseIdentifier: KYStatusCellIdentifier.ForwardCell.rawValue)
        
    }
    
    /// 加载模型
   func loadData() {
    
    
        // 加载
        KYStatus.loadStatus {(result, error) -> () in
            // 关闭刷新
            self.refreshControl?.endRefreshing()
            if error != nil {
                print(error)
                return
            }
            self.statuses = result
        }
    }
    
    
    
    // MARK: - Table view data source
    
    /// 返回多少行
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statuses?.count ?? 0
    }
    
    /// 数据源方法
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statuses![indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(KYStatusCellIdentifier.cellID(status), forIndexPath: indexPath) as! KYStatusCell
        
        cell.status = statuses![indexPath.row]
        return cell
    }
    
    /// 缓存计算行高  缓存行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let status = statuses![indexPath.row]
        if let h = status.rowHeight{
            
            return h
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(KYStatusCellIdentifier.cellID(status)) as? KYStatusCell
        status.rowHeight = cell!.rowHeight(status)
        return status.rowHeight!
    }
    
    
}
